package grpc

import (
	"context"
	"log"
	"net"
	"time"

	"daxin.my/test-netserver/protocol/grpc/helloworld"
	"google.golang.org/grpc"
)

// server is used to implement helloworld.GreeterServer.
type server struct {
	helloworld.UnimplementedGreeterServer
}

// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) {
	sleep := in.GetSleep()
	log.Printf("Received Grpc param: respbyte: %d, sleep: %dms\n", in.GetResponseByte(), sleep)
	time.Sleep(time.Duration(sleep) * time.Millisecond)
	message := make([]byte, in.GetResponseByte())
	for i := 0; i < len(message); i++ {
		message[i] = 'a'
	}
	return &helloworld.HelloReply{Message: string(message)}, nil
}

func StartGrpcServer(port string) {
	log.Printf("Start Grpc Server, port: %s\n", port)

	lis, err := net.Listen("tcp", ":"+port)
	if err != nil {
		log.Fatalf("Fail to listen: %v", err)
	}
	s := grpc.NewServer()
	helloworld.RegisterGreeterServer(s, &server{})
	if err := s.Serve(lis); err != nil {
		log.Fatalf("Fail to start Grpc Server: %v", err)
	}
}
